import React, { useState } from 'react';
import NumberField from '../../../../components/common/NumberField';
import StatefulCalculationCard from '../../../../components/common/StatefulCalculationCard';
import ExportData from '../../../../components/common/ExportCalculateData';
import type { ResultItem } from '../../../../../shared/types';

// 定义表单数据类型，使用与API一致的字段名
export interface FormValues {
  gamma_f: number;
  h_f: number;
  B_f: number;
  lambda_: number;
  theta: number;
}

// 计算结果类型定义
export interface FormResult {
  q_shallow: number;
}

// 计算初始值配置
const initialValues: FormValues = {
  gamma_f: 20.0,
  h_f: 1.0,
  B_f: 5.0,
  lambda_: 0.5,
  theta: 30,
};

// 计算卡片组件配置
const CalculationConfig = {
  key: 'ShallowBuriedCalculation',
  label: '浅埋溶洞计算',
  formKey: 'cave-soil-pressure-shallow',
  initialValues: initialValues,
  calculationType: 'cave-soil-pressure-shallow',
  resultFormatter: (data: FormResult) => [
    { key: 'q_shallow', name: '浅埋土压力q_shallow', value: data.q_shallow, unit: 'kN/m³' },
  ],
  renderFormFields: () => (
    <>
      <NumberField name="gamma_f" label="溶洞充填物重度γf (kN/m³)" required min={0} step={0.1} tooltip="溶洞充填物的重度" />
      <NumberField name="h_f" label="覆盖层厚度hf (m)" required min={0} step={0.1} tooltip="隧道拱部溶洞充填物拱顶的厚度" />
      <NumberField name="B_f" label="隧道宽度Bf (m)" required min={0} step={0.1} tooltip="隧道的宽度" />
      <NumberField name="lambda_" label="侧压力系数λ" required min={0} step={0.1} tooltip="隧道拱部溶洞充填物侧压力系数" />
      <NumberField name="theta" label="竖向滑面摩擦角θ (°)" required min={0} step={1} tooltip="溶洞充填物竖向滑面摩擦角" />
    </>
  ),
  optimizedFormula: "q_{\\text{shallow}} = \\gamma_f \\cdot h_f \\left[1 - \\frac{h_f}{B_f} \\lambda \\tan(\\theta)\\right]",
};

// 计算卡片组件实现
const ShallowBuriedCard: React.FC = () => {
  const [lastResults, setLastResults] = useState<ResultItem[] | null>(null);
  
  return (
    <StatefulCalculationCard
      title={CalculationConfig.label}
      formKey={CalculationConfig.formKey}
      initialValues={CalculationConfig.initialValues}
      renderFormFields={CalculationConfig.renderFormFields}
      calculationType={CalculationConfig.calculationType}
      resultFormatter={(data) => {
        const results = CalculationConfig.resultFormatter(data);
        setLastResults(results);
        return results;
      }}
      columnCount={1} // 使用1列布局
      tableHeight={300} // 设置表格高度为300px
      formula={CalculationConfig.optimizedFormula}
      exportComponent={(form) => (
        <ExportData
          siteName={CalculationConfig.label}
          inputs={form.getFieldsValue()}
          results={lastResults ? Object.fromEntries(lastResults.map(r => [r.key, r.value])) : {}}
          calculationType={CalculationConfig.calculationType}
        />
      )}
    />
  );
};

export default ShallowBuriedCard;